package com.hongdee.scm.approvalflow.service.impl;

import com.hongdee.common.util.TokenUtil;
import com.hongdee.scm.allocationorder.service.ITScmAllocationOrderService;
import com.hongdee.scm.approvalflow.dao.ITScmApprovalflowDao;
import com.hongdee.scm.approvalflow.entity.TScmApprovalflow;
import com.hongdee.scm.approvalflow.service.ITScmApprovalflowService;
import com.hongdee.scm.common.service.impl.Common;
import com.hongdee.scm.pushMessage.dao.ITScmPushMsgDao;
import com.hongdee.scm.pushMessage.service.ITScmPushMsgService;
import jdk.nashorn.internal.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 名  称:TScmApprovalflowServiceImpl
 * 类  型:class
 * 描  述:
 * 路  径:com.hongdee.scm.approvalflow.service.impl
 * 作  者: 术洪超
 * 日  期:2017-06-14 10:41
 */
@Service
public class TScmApprovalflowServiceImpl implements ITScmApprovalflowService {

    String tabName = "T_SCM_APPROVALFLOW";
    String entityName = "TScmApprovalflow";
    @Autowired
    private ITScmApprovalflowDao itScmApprovalflowDao;

    @Autowired
    private ITScmAllocationOrderService itScmAllocationOrderService;

    @Override
    public Map info(String pId,String uid) throws Exception {

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select * from " + tabName +" where status = '1' ");
        if (!StringUtils.isEmpty(pId)) {
            sql.append(" and approvalflow_p_id = ?");
            params.add(pId);
        }
        if(!StringUtils.isEmpty(TokenUtil.getCompanyId(uid))){
            sql.append(" and company_id = ?");
            params.add(TokenUtil.getCompanyId(uid));
        }
        sql.append(" order by create_time desc limit 1");
        return this.itScmApprovalflowDao.info(sql.toString(), params.toArray());
    }

    @Override
    public TScmApprovalflow save(TScmApprovalflow data, String uid) throws Exception {

        if (data.getId() == null) {
            data.setStatus("1");
            data.setOperator(uid);
            data.setCreateUser(uid);
            data.setCreateTime(Calendar.getInstance().getTimeInMillis());
        } else {
            data.setUpdateUser(uid);
            data.setUpdateTime(Calendar.getInstance().getTimeInMillis());
        }

        data.setCompanyId(TokenUtil.getCompanyId(uid));
        this.itScmApprovalflowDao.saveOrUpdate(data);
        return data;
    }
//停用启用
    @Override
    public void update(String id, String status) throws Exception {
        Map param = new HashMap();
        StringBuffer hql = new StringBuffer();
        hql.append("update " + entityName + " set status=:status where id= :id");
        param.put("status", status);
        param.put("id", id);
        this.itScmApprovalflowDao.update(hql.toString(), param);

    }

    @Override
    public Map page(String start, String limit, Map data, String uid) throws Exception {

        StringBuffer sql = new StringBuffer();
        List params = new ArrayList();
        sql.append("select * from " + tabName);
        Common common = new Common();
        Boolean hasWhere = false;
        if (data.get("approvalflowPId") != null && !StringUtils.isEmpty(data.get("approvalflowPId"))) {
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" approvalflow_p_id = ?");
            params.add(data.get("approvalflowPId"));
        }

        String cid = TokenUtil.getCompanyId(uid);
        if(cid!=null&&!cid.equals("")){
            hasWhere = common.appendWhereIfNeed(sql, hasWhere);
            sql.append(" company_id = ?");
            params.add(cid);
        }
        sql.append(" order by create_time");
        return this.itScmApprovalflowDao.page(sql.toString(), params.toArray(), start, limit);
    }

    /**
     * 根据调拨类型查询是否存在审批开始;返回true为存在开始，否之不存在
     * @param approvalflowPId
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public boolean isExistApprovalStart (String approvalflowPId,String uid) throws Exception{
        if(approvalflowPId.equals("")){
            throw new Exception("调拨类型不可为空！");
        }
        if(this.itScmApprovalflowDao.info("select * from "+tabName+" where  status='1' and approvalflow_p_id = ? and start_status='开始' and company_id=?",approvalflowPId,TokenUtil.getCompanyId(uid)).isEmpty()){
            return false;
        }else {return true;}
    }
    // 根据调拨类型查询审批是否完整（审批结束+审批流完整）
    //返回true为存在开始，否之不存在
    public boolean isWholeApprovalFlow (String approvalflowPId,String startStatus,String uid) throws Exception{
        StringBuffer sqlBuf = new StringBuffer();
        List params = new ArrayList();
        sqlBuf.append("select * from "+tabName +" where status='1' and company_id=? ");
        params.add(TokenUtil.getCompanyId(uid));
        if(approvalflowPId!=null){
            sqlBuf.append(" and approvalflow_p_id = ? ");
            params.add(approvalflowPId);
        }else {
            throw new Exception("调拨类型不可为空！");
        }
        if(startStatus!=null){
            sqlBuf.append(" and start_status = ? ");
            params.add(startStatus);
        }else {
            throw new Exception("当前审批状态为空！");
        }
        Map map = this.itScmApprovalflowDao.info(sqlBuf.toString(),params.toArray());
        //节点审批流设置下个节点不为空，并且下个节点不为结束,递归查询
        if(map.isEmpty()){
            throw new Exception("审批流不完整，请维护审批流！");
        }
        if(map.get("circulationStatus")==null||StringUtils.isEmpty(map.get("circulationStatus"))){
                throw new Exception("下个节点为空，请维护审批流！");
        }
        if(!String.valueOf(map.get("circulationStatus")).equals("结束")){
            this.isWholeApprovalFlow(approvalflowPId,map.get("circulationStatus").toString(),uid);
        }
        return true;
    }
    //调拨单提交按钮
    @Override
    public Map commitApproval (String approvalflowPId,String id,String uid) throws Exception{
        if(!StringUtils.isEmpty(this.itScmApprovalflowDao.info("select * " +
                " from t_scm_allocation_order where id = ? ",id).get("applicant"))){
            throw  new Exception("已提交审批！");
        }
        if(this.isWholeApprovalFlow(approvalflowPId,"开始",uid)) {
            Map map = new HashMap();
            //查询审批开始下个节点状态
            if(!approvalflowPId.equals("")){
            List list = this.itScmApprovalflowDao.list("select * from "+tabName+" where status='1' and start_status='开始'" +
                    " and approvalflow_p_id = ? and company_id=? ",approvalflowPId,TokenUtil.getCompanyId(uid));
            map = (Map) list.get(0);
            }else {
                throw new Exception("审批类型不能为空！");
            }
            Date d = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //给调拨单赋值(审批状态，申请人，申请时间)
            this.itScmApprovalflowDao.executeSQL("update t_scm_allocation_order set current_approval_status=?," +
                    " applicant=?,submit_date=? where id = ? ",map.get("circulationStatus"),uid,df.format(d), id);
           //个推透传内容
           return this.pushMessage(approvalflowPId,id,uid,map.get("circulationStatus").toString());
        }else{
            throw new Exception("审批流不完整，请维护审批流！");
        }
    }

    @Override
    public Map pushMessage(String approvalflowPId,String id,String uid,String status) throws Exception{

        Map map = new HashMap();
        //个推消息传送
        List list = this.itScmApprovalflowDao.list("select id from t_bc_user where  id in (" +
                " select u_id from t_bc_role_user where r_id in (select start_roles" +
                " from t_scm_approvalflow where start_status = ? and status = '1' and company_id=?)) and o_id in (" +
                " select id from t_bc_organ where o_p_id =?)",status,TokenUtil.getCompanyId(uid),TokenUtil.getCompanyId(uid));
        List list1 = this.itScmApprovalflowDao.list("select count(1) as approvalNum from t_scm_allocation_order" +
                " where company_id =? and current_approval_status = ?" +
                " group by current_approval_status",TokenUtil.getCompanyId(uid),status);
        Map mm = (Map) list1.get(0);
        map.put("content","待审批数量:"+mm.get("approvalNum")+",请及时审批！");
        map.put("title","您有新的调拨单待审批！");
        map.put("type",1); //调拨
        map.put("saId",list);
        map.put("data",mm);
        return map;
    }
    //退回单据
    @Override
    public void backApproval (String id,String uid) throws Exception{
        if(!id.equals("")){
            this.itScmApprovalflowDao.executeSQL("update t_scm_allocation_order set current_approval_status=null,applicant=null," +
                    " submit_date=null where id = ? ",id);
        }else{
            throw new Exception("单据ID不能为空！");
        }
    }
}
